<template>
  <div>
    <el-form
      :model="formConfig.formData"
      ref="form"
      :label-width="formConfig.labelWidth ? formConfig.labelWidth : 'auto'"
      :class="formConfig.class ? formConfig.class : 'yl-form-item__content'"
      :rules="formConfig.editRules"
      :disabled="!isFormList"
    >
    <el-row>
      <el-col
        v-for="item in formConfig.columns"
        :key="item.prop"
        :span="(formConfig.spanWidth || item.spanWidth) ? (formConfig.spanWidth || item.spanWidth) : 24"
      >
        <el-form-item
          :label="item.label"
          :prop="item.prop"
        >
          <!-- 输入框 -->
          <el-input
            v-if="item.type === 'input'"
            type="text"
            v-model="formConfig.formData[item.prop]"
            :disabled="item.disabled"
            :placeholder="'请输入' + item.label"
            :maxlength="item.length"
            clearable
            show-word-limit
          />

          <!-- 密码框 -->
          <el-input
            v-if="item.type === 'password'"
            type="password"
            v-model="formConfig.formData[item.prop]"
            :disabled="item.disabled"
            :placeholder="'请输入' + item.label"
            clearable
            show-password
          />

          <!-- 文本框 -->
          <el-input
            v-if="item.type === 'textarea'"
            type="textarea"
            v-model="formConfig.formData[item.prop]"
            :disabled="item.disabled"
            :placeholder="'请输入' + item.label"
            :rows="8"
            :maxlength="item.length"
            clearable
            show-word-limit
          />

          <!-- 下拉框 -->
          <el-select
            v-if="item.type === 'select'"
            v-model="formConfig.formData[item.prop]"
            :disabled="item.disabled"
            :placeholder="'请输入' + item.label"
            clearable
            filterable
            :multiple="item.multiple"
          >
            <el-option
              v-for="(i, j) in item.options"
              :key="j"
              :label="i.label"
              :value="i.value"
            />
          </el-select>

          <!-- 联级选择器 -->
          <el-cascader
            v-if="item.type === 'cascader'"
            v-model="formConfig.formData[item.prop]"
            :disabled="item.disabled"
            ref="cascader"
            :props="item.config"
            clearable
            :options="item.options"
            @change="handleCascaderChange"
          />

          <!-- 日期时间选择器(单) -->
          <el-date-picker
            v-if="item.type === 'time'"
            v-model="formConfig.formData[item.prop]"
            :disabled="item.disabled"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期时间"
          />

          <!-- 上传组件 -->
          <YlUpload
            v-if="item.type === 'upload'"
            :listType="item.listType"
            :isNormal="item.isNormal"
            :action="item.action"
            :limit="item.limit"
            :disabled="item.disabled"
            :name="item.name"
            :drag="item.drag"
            :accept="item.accept"
            :file-arr="fileArr"
            @file-List="getFileList"
          />

          <!-- 日期时间选择器(双) -->
          <el-date-picker
            v-if="item.type === 'timeRange'"
            v-model="formConfig.formData[item.prop]"
            :disabled="item.disabled"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleTimeRangeChange"
          />

          <!-- 多选框 -->
          <el-checkbox-group
            v-if="item.type === 'checkbox'"
            v-model="formConfig.formData[item.prop]"
            :disabled="item.disabled"
          >
            <el-checkbox
              v-for="(c, n) in item.options"
              :key="n"
              :label="c.label"
              :value="c.value"
            />
          </el-checkbox-group>

          <!-- 单选框 -->
          <el-radio-group
            v-if="item.type === 'radio'"
            v-model="formConfig.formData[item.prop]"
            :disabled="item.disabled"
          >
            <el-radio
              v-for="(r, g) in item.options"
              :key="g"
              :label="r.label"
              :value="r.value"
            />
          </el-radio-group>

          <YlTree
            ref="yltree"
            v-if="item.type === 'tree'"
            v-model="formConfig.formData[item.prop]"
            :disabled="item.disabled"
            :treeConfig="item.treeConfig"
            :defaultCheckedKeys="item.defaultCheckedKeys"
            @check-node="getCheckNode"
          />
        </el-form-item>
      </el-col>
    </el-row>
      <el-form-item class="yl-form-btn-list" v-if="isFormList" style="margin: 0; text-align: center">
        <div style="display: inline" v-for="(item, index) in formConfig.btnMethod" :key="index">
          <YlButton uiType="default" @click="getFormData" :loading="isBtnLoading" v-if="item === 'submit'">提 交</YlButton>
          <YlButton uiType="default" @click="changeFormData" :loading="isBtnLoading" v-if="item === 'save'">保 存</YlButton>
          <YlButton uiType="default" btnType="success" @click="handleOpenDialog(true)" :loading="isBtnLoading" v-if="item === 'resolve'">通 过</YlButton>
          <YlButton uiType="default" btnType="danger" @click="handleOpenDialog(false)" :loading="isBtnLoading" v-if="item === 'reject'">驳 回</YlButton>
          <YlButton uiType="default" btnType="info" @click="handleDialogClose" v-if="item === 'cancel'">取 消</YlButton>
        </div>
      </el-form-item>
    </el-form>

    <!-- 通过驳回弹层 -->
    <el-dialog title="驳回原因" width="800px" :visible.sync="resolveOrRjectDialog">
      <exam-prj :rejectData="rejectData" @init-state="getInitState"></exam-prj>
    </el-dialog>
  </div>
</template>

<script>
import YlUpload from './src/upload'
import ExamPrj from './src/examPrj'
import {
  MessageBox
} from 'element-ui'
export default {
  name: 'YlForm',
  components: {
    YlUpload,
    ExamPrj
  },

  props: {
    formConfig: {
      type: Object,
      default: () => ({})
    },
    isFormList: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      isBtnLoading: false,
      resolveOrRjectDialog: false,
      rejectData: {},
      fileArr: []
    }
  },

  mounted () {
    this.showFile()
  },

  methods: {
    // 图片回显
    showFile () {
      if (
        this.formConfig.formData.additional_file &&
        typeof this.formConfig.formData.additional_file === 'string'
      ) {
        let name = this.formConfig.formData.additional_file.split('/').pop()
        this.fileArr.push({
          url: this.formConfig.formData.additional_file_url,
          path: this.formConfig.formData.additional_file,
          name
        })
      }
    },
    // 新增form操作
    getFormData () {
      this.chargeCascaderData()
      // 防止JSON传递参数时自动过滤函数机制
      let api = typeof this.formConfig.addApi === 'string'
        // eslint-disable-next-line no-eval
        ? eval(this.formConfig.addApi)
        : this.formConfig.addApi
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.isBtnLoading = true
          api(this.formConfig.formData)
            .then(res => {
              this.$modal.success(this, '操作成功' || res)
              this.isBtnLoading = false
              this.$emit('init-state', true)
            })
            .catch(() => {
              this.isBtnLoading = false
            })
        }
      })
    },

    // 修改form操作
    changeFormData () {
      this.chargeCascaderData()
      // 防止JSON传递参数时自动过滤函数机制
      let api = typeof this.formConfig.changeApi === 'string'
        // eslint-disable-next-line no-eval
        ? eval(this.formConfig.changeApi)
        : this.formConfig.changeApi
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.isBtnLoading = true
          // 防止JSON传递参数时自动过滤函数机制
          api(
            this.formConfig.changeId,
            this.formConfig.formData
          ).then(res => {
            this.$modal.success(this, '操作成功' || res)
            this.isBtnLoading = false
            this.$emit('init-state', true)
          })
            .catch(() => {
              this.isBtnLoading = false
            })
        }
      })
    },

    // 时间选择器(双)
    handleTimeRangeChange (value) {
      let item = this.formConfig.columns
      for (let i in item) {
        if (
          item[i].type === 'timeRange' &&
          Object.prototype.toString.call(this.formConfig.formData[item[i].prop]) === '[object Array]'
        ) {
          Object.assign(this.formConfig.formData, item[i].timer)
          this.formConfig.formData.start_time = value[0]
          this.formConfig.formData.end_time = value[1]
        }
      }
    },

    // 联级选择器 整合数据
    chargeCascaderData () {
      let item = this.formConfig.columns
      for (let i in item) {
        if (
          item[i].type === 'cascader' &&
          Object.prototype.toString.call(this.formConfig.formData[item[i].prop]) === '[object Array]'
        ) {
          let initCacader = this.formConfig.formData[item[i].prop]
          this.formConfig.formData[item[i].prop] = [...initCacader].pop()
        }
      }
    },

    // 联级选择器 获取id
    handleCascaderChange () {
      let item = this.formConfig.columns
      for (let i in item) {
        if (
          item[i].type === 'cascader' &&
          this.$refs['cascader'][0].getCheckedNodes().length !== 0
        ) {
          this.formConfig.formData[item[i].prop] = this.$refs['cascader'][0].getCheckedNodes()[0].data.nns_id
        }
      }
    },

    // 获取上传对象
    getFileList (res) {
      let fileList = res.response.data.success_list
      let fileArr = []
      for (let i in fileList) {
        fileArr.push(fileList[i].path)
      }
      let file = arrangeDataList(fileArr, true)
      // formData与Columns比对赋值
      let item = this.formConfig.columns
      for (let i in item) {
        if (item[i].type === 'upload') {
          this.formConfig.formData[item[i].prop] = file
        }
      }
    },

    // 树级组件获取值
    getCheckNode (arr) {
      this.formConfig.formData.pris_no = arrangeDataList(arr, true)
    },

    // 关闭dialog
    handleDialogClose () {
      this.$emit('close-dialog', false)
      this.$refs['form'].resetFields()
      this.resolveOrRjectDialog = false
    },

    // 弹出层用于 --- 审核项目
    handleOpenDialog (state) {
      // 防止JSON传递参数时自动过滤函数机制
      let api = typeof this.formConfig.stateApi === 'string'
        // eslint-disable-next-line no-eval
        ? eval(this.formConfig.stateApi)
        : this.formConfig.stateApi
      if (state) {
        MessageBox.confirm('是否确认审核通过?', '提示', {
          confirmButtonText: '确认',
          cancelButtonClass: '取消',
          type: 'warning'
        }).then(() => {
          api({
            id: this.formConfig.changeId,
            op: 1
          }).then(res => {
            this.$modal.success(this, '操作成功')
            this.$emit('init-state', true)
          })
            .catch(() => {
              this.$modal.info(this, '操作已取消')
            })
        })
      } else {
        this.rejectData = {
          id: this.formConfig.changeId,
          op: 0,
          api: this.formConfig.stateApi
        }
        this.resolveOrRjectDialog = true
      }
    },

    // 驳回专用
    getInitState (val) {
      if (val) {
        this.resolveOrRjectDialog = false
        this.$emit('init-state', val)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .yl-form-btn__list {
    /deep/ .el-form-item__content {
      display: flex;
      .el-button {
        &:last-child {
          margin-left: 10px;
        }
      }
    }
  }
  .el-form {
    width: 100%;
  }
</style>
